package com.example.studentmanager.utils;

import java.io.*;


/**
 * 对象的序列化、反序列化，便于传输、存储对象
 */

public class SerializeUtil {
    public byte[]   serializeObject(Object b){
        byte[] bytes;
        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream;

        try {
            //ObjectOutputStream outputStream=new ObjectOutputStream(new FileOutputStream("C:/Users/liudehua/IdeaProjects/algorithmExercise/src/sera.txt"));
            objectOutputStream=new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeUTF("UTF-8");
            objectOutputStream.writeObject(b);
            bytes=byteArrayOutputStream.toByteArray();
            return bytes;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static Object unseralize(byte[] byt){
       Object o= null;
       //ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(byt);
        ObjectInputStream objectInputStream;

        try {
            //ObjectInputStream in=new ObjectInputStream(new FileInputStream("C:/Users/liudehua/IdeaProjects/algorithmExercise/src/sera.txt"));
            objectInputStream=new ObjectInputStream(byteArrayInputStream);
            objectInputStream.readUTF();
            o=objectInputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return o;
    }
}
